package com.mobi.cacti.common;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import com.mobi.cacti.LoginActivity;
import com.mobi.cacti.dt.dtItem;
import com.mobi.cacti.model.dtRespListOfCircuitDatas;
import com.mobi.cacti.model.mdRespListOfDatas;
import com.mobi.cacti.rabbit.response.Cache;

public class Utils {
	public static String valStr(Object obj) {
		String result = "";
		if(obj != null)
			result = obj.toString().trim();
		
		return result;
	}
	public static String valStr2(Object obj) {
		String result = "";
		if(obj != null){
			result = obj.toString().replace("\"", "");
			result = result.trim();
		}
		
		return result;
	}
	
	public static int valInt(Object obj) {
		try{
			int result = 0;
			if(obj != null)
				result = Integer.parseInt(obj.toString().trim());
			
			return result;
		}
		catch (Exception e) {
			return 0;
		}
	}
	
	public static String getKeyContactFromCircuit(String mCircuitID, Map<String, mdRespListOfDatas> mContactMap) {
		String result = "";
		for( String keyContact: mContactMap.keySet() ){
			mdRespListOfDatas contact  = mContactMap.get(keyContact);
			for( String keyCircuit: contact.resp_List_Of_Circuit_datas.keySet() ){
				dtRespListOfCircuitDatas dtCircuit = contact.resp_List_Of_Circuit_datas.get(keyCircuit);
				if(dtCircuit.CircuitID.equalsIgnoreCase(mCircuitID))
					return keyContact;	
			}
		}
		
		return result;
	}
	public static ArrayList<dtItem> getListPhoneAll() {
		ArrayList<dtItem> result = new ArrayList<dtItem>();
//		dtItem dt;
//		Map<String, mdRespListOfDatas> contactMap = Cache.reqW4CusInfo.Resp_List_of_Data;
//		for( String keyContact: contactMap.keySet() ){
//			mdRespListOfDatas contact  = contactMap.get(keyContact);
//			if(! isExistValInArrList(contact.ContactPerName , result)){
//				dt = new dtItem();
//				dt.item_name = contact.ContactPerName;
//				dt.item_no = contact.ContactPerTel;
//				result.add(dt);
//			}				
//		}		
		return result;
	}
	
	public static ArrayList<dtItem> getListEmailAll() {
		ArrayList<dtItem> result = new ArrayList<dtItem>();
//		dtItem dt;
//		Map<String, mdRespListOfDatas> contactMap = Cache.reqW4CusInfo.Resp_List_of_Data;
//		for( String keyContact: contactMap.keySet() ){
//			mdRespListOfDatas contact  = contactMap.get(keyContact);
//			if(! isExistValInArrList(contact.ContactPerName , result)){
//				dt = new dtItem();
//				dt.item_name = contact.ContactPerName;
//				dt.item_no = contact.ContactPerEmail;
//				result.add(dt);
//			}				
//		}		
		return result;
	}
	
	public static boolean isExistValInArrList(String mValCheck, ArrayList<dtItem> mArrList){
		for(int i =0;i < mArrList.size();i++){
			if(mArrList.get(i).item_name.equals(mValCheck))
				return true;
		}
		return false;
	}
		
	//================================================ dialog message
	public static ProgressDialog pd;
	/*
	public static AlertDialog loadingDialog;
    public static void showLoadingDialog(final String message,final Activity activity) {
        if (activity != null) {
            activity.runOnUiThread(new Runnable() {
                public void run() {    
                	final LinearLayout linearLayout = new LinearLayout(activity);
                    linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT)); 
                    linearLayout.setBackgroundColor(Color.parseColor("#FFFFFF"));
                    linearLayout.setOrientation(1); 
                    
                    final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                    builder.setView(linearLayout);
                    loadingDialog = builder.create();
                    
                    LayoutInflater inflater = (LayoutInflater) activity.getLayoutInflater();
                    View loadingView = inflater.inflate(R.layout.loading, null);          
	               	TextView tvStatusMessage = (TextView) loadingView.findViewById(R.id.tvStatusMessage);
	               	tvStatusMessage.setText(message);
	               	tvStatusMessage.setWidth(350);
	               	tvStatusMessage.setGravity(Gravity.CENTER);
	               	linearLayout.addView(loadingView);  
	               	
	               	//final ImageView imgView1 = new ImageView(activity);
	               	//imgView1.setImageResource(R.drawable.finish);
	               	//linearLayout.addView(imgView1); 
	               	loadingDialog.show(); //end dialog custom
                	 
                    //loadingDialog = ProgressDialog.show(activity, "", message, true, false);
                    //loadingDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                }
            });
        }
    }
    */
    public static void showDialogMsgInThread(final String message, final String strTitle,final Activity activity) {
        if (activity != null) {
        	try 
        	{
				  Thread thread = new Thread()
		            {
		                @Override
		                public void run() {
		                	 activity.runOnUiThread(new Runnable() {
		                         public void run() {
		                         	showDialogMsg(message,strTitle,activity);
		                         }
		                     });               
		                }
		            };
		            thread.start();  
	        }
        	catch (Exception e){}
        }
    }    
    public static void showDialogMsg(String strMsg, String strTitle,Activity activity) {
        new AlertDialog.Builder(activity).setMessage(strMsg).setTitle(strTitle).setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.dismiss();
            }
        }).create().show();
    }
    public static void ToastThread(final Activity activity, final String message)
    {
    	try 
    	{
			  Thread thread = new Thread()
	            {
	                @Override
	                public void run() {
	                	 activity.runOnUiThread(new Runnable() {
	                         public void run()
	                         {
	                             Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
	                         }
	                     });          
	                }
	            };
	            thread.start();  
        }
    	catch (Exception e){}
    }
    
    public static void catchFn(String mStrMsg,Exception ex, Activity atv)
    {
    	 String strErr = (ex != null) ? ex.getMessage() : "NL";
         Log.e(mStrMsg,"catch:" +strErr);
         ToastThread(atv, strErr);
         
         Intent i = new Intent(atv,LoginActivity.class);
         atv.startActivity(i);
         atv.finish();
    }
    
    //======================================== picture function
    public static Bitmap getBitmap(final String mFullPathPic)
    {
        Bitmap bMap = null;
        try 
        {
            bMap = BitmapFactory.decodeFile(mFullPathPic);
            return bMap;
        }
        catch (Exception e)
        {
            return null;
        }
    }
    public static Bitmap getBitmapResize1(final String mFullPathPic,final int mWidth, final int mHeight){
        Bitmap bitmap2;
        try 
        {
            final File f = new File(mFullPathPic);
            if (! f.exists())
            {
                return null;
            }
            //Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();            
            o2.inJustDecodeBounds = false;//Decode bitmap with inSampleSize set
            o2.inSampleSize= 1;//scale;
            o2.inPurgeable = true;   
            o2.inInputShareable = true;            
            bitmap2 = BitmapFactory.decodeStream(new FileInputStream(f), null, o2);   
            o2 = null;
            
            bitmap2 = Bitmap.createScaledBitmap(bitmap2, mWidth, mHeight, true);// fix size w h : 100%(mWidth=100,mHeight=100)
            return bitmap2;
        } 
        catch (Exception e)
        {
            String err = (e==null || e.getMessage()==null)?"Exception failed":e.getMessage();//error: onActivityResult println needs a message
            Log.e("getBitmapResize1",err);
            return null;
        }
        finally 
        {
            bitmap2 = null;
        }
    }   
   
    //=============================================== datetime function
	public static String getReqSessionID()
	{
		 final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
	     return "COMiQ"+dateFormat.format(Calendar.getInstance().getTime());		
	}
	public static String getDateNowYMD()
	{
		 final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	     return dateFormat.format(Calendar.getInstance().getTime());		
	}
	public static String getDateNowDMY()
	{
		 final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
		 String strD = dateFormat.format(Calendar.getInstance().getTime());
	     return cYmdToDmy(strD,false);		
	}
	public static String getTimeNow()
	{
		 final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
	     return dateFormat.format(Calendar.getInstance().getTime());		
	}
	public static String getDateTimeNow()
	{
		 final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	     return dateFormat.format(Calendar.getInstance().getTime());		
	}
	//mFormatDateTime = "yyyy-MM-dd HH:mm:ss" return date
	public static Date convertStrToDateTime(String mDateTime,String mFormatDateTime)
	{
		try{
			final SimpleDateFormat dateFormat = new SimpleDateFormat(mFormatDateTime);		     		
			Date convertedDate = new Date();
			convertedDate = dateFormat.parse(mDateTime);
			
			return convertedDate;
		}catch(Exception e){
			return null;
		}		 
	}
	//mFormatDateTime =  "yyyy(thai/Eng)-MM-dd"  return "dd/MM/yyyy(thai)"
	//mFormatDateTime =  "yyyy(thai/Eng)-MM-dd  HH:mm:ss"  return "dd/MM/yyyy(thai)  HH:mm:ss"
	//mFormatDateTime =  "yyyy(thai/Eng)/MM/dd"  return "dd/MM/yyyy(thai)"
	public static String cYmdToDmy(String mDateTime, Boolean wantYearEng)
	{
		try
		{
			 int yyyy;
			   String result,dd,mm;
			   String[] arr1,arr2;
			   result = "";
			   
			   arr1 = mDateTime.split(" ");
			   arr2 = arr1[0].split("-");
			   
			   if(arr2.length == 3)
			   {
				   yyyy =  Integer.parseInt(arr2[0]);
				   if(yyyy < 100) 
					   return mDateTime;//missing format yyyy-MM-dd
				   else
				   {
					   if(! wantYearEng)
					   {
						   if(yyyy <= 2500)yyyy += 543;	
					   }
					   else
					   {
						   if(yyyy > 2500)yyyy -= 543;	
					   }
					   mm = arr2[1];
					   dd = arr2[2];
					   result = dd + "/" + mm + "/" + yyyy; 
				   }
			   }
			   else
			   {
				   //format dd/mm/yyyy : check year
				   arr2 = arr1[0].split("/");
				   if(arr2.length == 3)
				   {
					   mm = arr2[1];
					   dd = arr2[0];
					   yyyy =  Integer.parseInt(arr2[2]);
					   if(! wantYearEng)
					   {
						   if(yyyy <= 2500)yyyy += 543;	
					   }
					   else
					   {
						   if(yyyy > 2500)yyyy -= 543;	
					   }
					   result = dd + "/" + mm + "/" + yyyy; 
				   }
				   else
				   {
					   result =  mDateTime;	
				   }				   
			   }
			   
			   if(arr1.length > 1)
				   result = result + " " + arr1[1];
			   
			   return result;
		}
		catch (Exception e) 
		{
			return mDateTime;
		}
	}
	//mFormatDateTime = "dd/MM/yyyy(thai)"   return "yyyy(thai/Eng)-MM-dd"
	//mFormatDateTime =  "dd/MM/yyyy(thai)  HH:mm:ss"    return "yyyy(thai/Eng)-MM-dd HH:mm:ss"
	public static String cDmyToYmd(String mDateTime,Boolean wantYearEng)
	{
		try
		{
			 int yyyy;
			   String result,dd,mm;
			   String[] arr1,arr2;
			   result = "";
			   
			   arr1 = mDateTime.split(" ");
			   arr2 = arr1[0].split("/");
			   
			   if(arr2.length == 3)
			   {
				   yyyy =  Integer.parseInt(arr2[2]);
				   if(yyyy < 100) 
					   return mDateTime;//missing format yyyy-MM-dd
				   else
				   {
					   if(! wantYearEng)
					   {
						   if(yyyy <= 2500)yyyy += 543;	
					   }
					   else
					   {
						   if(yyyy > 2500)yyyy -= 543;	
					   }
					   mm = arr2[1];
					   dd = arr2[0];
					   result = yyyy+"-"+mm+"-"+dd; 
				   }
			   }
			   else
				   result =  mDateTime;			
			   
			   if(arr1.length > 1)
				   result = result + " " + arr1[1];
			   
			   return result;
		}
		catch (Exception e) 
		{
			return mDateTime;
		}
	}
	
	//======================================================= read write file
	
    //return path root and create folder if not exist
  	public static String getRootDirectory(String userId,String curcuit){
  		 File fiileFloder;
  		 //make dir isurvey_lite
  		 String floder = Environment.getExternalStorageDirectory()+ File.separator + "cacti"+ File.separator; 
  		 fiileFloder = new File(floder);		 
  		 if (!fiileFloder.exists()) fiileFloder.mkdirs();
  		 
  		 //make dir userId
  		 if(!userId.trim().equals(""))
  		 {
  			 floder += userId+ File.separator;
  			 fiileFloder = new File(floder);		 
  			 if (!fiileFloder.exists()) fiileFloder.mkdirs();
  		 }
  		 
  		 //make dir circuit
  		 if(!curcuit.trim().equals(""))
  		 {
  			 floder += curcuit+ File.separator;
  			 fiileFloder = new File(floder);		 
  			 if (!fiileFloder.exists()){
  				fiileFloder.mkdirs();
  			 }
  		 }
  		 
  		return floder;
  	 }
  	
	 public static boolean storeBitmap(final String mUserId, final String mCaseNo, final String mfileName,final String mFloderName, final Bitmap bitmap,int Qaulity) 
	    {
	        boolean isSuccess = false;
	        OutputStream outputStream = null;
	        try
	        {
	        	String floder = getRootDirectory(mUserId, mCaseNo);
	        	final File fiileFloder = new File(floder);
				if (!fiileFloder.exists())
					fiileFloder.mkdirs();
				
	            final String path = floder  + mfileName + ".jpg";
	            File fileInfo = new File(path);
	            if (fileInfo.exists())
				{
					fileInfo.delete();				
				}
	            outputStream = new BufferedOutputStream(new FileOutputStream(fileInfo));
	            //bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); //master
	            bitmap.compress(Bitmap.CompressFormat.JPEG, Qaulity, outputStream);//visid remark: resize qaulity 0-100 
	            outputStream.flush();
	            isSuccess = true;
	        }
	        catch (Exception e)
	        {
	            String err = (e.getMessage()==null)?"Exception failed":e.getMessage();//error: onActivityResult println needs a message
	            Log.e("onActivityResult",err);
	        }
	        finally
	        {
	            if (null != outputStream)
	            {
	                try
	                {
	                    outputStream.close();
	                }
	                catch (IOException e)
	                {
	                    // Ignore Exception
	                }
	            }
	        }

	        return isSuccess;
	    }
	 
	 public static boolean SaveDataToFile(String mFullPath,String mData) {
			try {
				final File fileInfo = new File(mFullPath);
				if (fileInfo.exists())
				{
					fileInfo.delete();				
				}
				fileInfo.createNewFile();

				BufferedWriter writer = new BufferedWriter(new FileWriter(fileInfo,false));// append = true
				writer.write(mData);
				writer.close();

				return true;
			} catch (Exception e) {
				Log.e("storeNotInternet", "err:" + e.getMessage());
				return false;
			}
	 }
	 public static String loadDataFromFile(String mFullPath) {
		try {
			//ex: mnt/sdcard/isurvey_lite/132/isurvey_lite.caselist
			final File file = new File(mFullPath);
			String result = "";
			if (file.exists()) {
				final BufferedReader reader = new BufferedReader(new FileReader(file));
				final StringBuilder builder = new StringBuilder();
				String temp = "";
				while ((temp = reader.readLine()) != null) {
					builder.append(temp);
				}
				reader.close();
				result = builder.toString();				
			}

			return result;
		} catch (Exception e) {
			Log.e("loadDataFromFile", "err:" + e.getMessage());
			return "";
		}
	}
	 
	public static void DeleteRecursive(final File dir)
    {
        Log.d("DeleteRecursive", "DELETEPREVIOUS TOP" + dir.getPath());
        if (dir.isDirectory())
        {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++)
            {
                File temp = new File(dir, children[i]);
                if (temp.isDirectory())
                {
                    Log.d("DeleteRecursive", "Recursive Call" + temp.getPath());
                    DeleteRecursive(temp);
                }
                else
                {
                    Log.d("DeleteRecursive", "Delete File" + temp.getPath());
                    boolean b = temp.delete();
                    if (b == false)
                    {
                        Log.d("DeleteRecursive", "DELETE FAIL");
                    }
                }
            }

            dir.delete();
        }
    }
     
	public static Boolean DeleteFile(final String mFilePath){
	     try
	     {
	         final File fileInfo = new File(mFilePath);
	         if (fileInfo.exists()) 
	             fileInfo.delete();
	             
	         return true;
	     }
	     catch (Exception e) 
	     {
	         Log.e("DeleteFileTmpNet","err:" + e.getMessage());
	        return false;
	     }       
     }
 
}
